<template>
  <div class="schedule-container">
    <div class="page-header">
      <div class="title-section">
        <h2>护士排班表</h2>
        <span class="subtitle">{{ queryParams.year }}年{{ queryParams.month }}月{{ queryParams.stage === 1 ? '上' : '下' }}半月</span>
      </div>
      <el-button type="primary" class="add-btn" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增排班
      </el-button>
    </div>

    <div class="filter-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="护士编号">
          <el-input v-model="queryParams.nurseCode" placeholder="请输入护士编号" />
        </el-form-item>
        <el-form-item label="年份">
          <el-input v-model="queryParams.year" placeholder="请输入年份" />
        </el-form-item>
        <el-form-item label="月份">
          <el-input v-model="queryParams.month" placeholder="请输入月份" />
        </el-form-item>
        <el-form-item label="阶段">
          <el-select v-model="queryParams.stage" placeholder="请选择阶段" style="width: 100px;" >
            <el-option label="上半月" :value="1" />
            <el-option label="下半月" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getScheduleList">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="schedule-grid">
      <!-- 日期表头 -->
      <div class="schedule-header">
        <div class="name-cell">姓名</div>
        <div v-for="day in days" :key="day.date" class="date-cell">
          {{ day.label }}
        </div>
      </div>

      <!-- 排班内容 -->
      <div class="schedule-body">
        <div v-for="(nurse, index) in scheduleData" :key="index" class="schedule-row">
          <div class="name-cell">{{ nurse.nurseName }}</div>
          <div v-for="day in days" :key="day.date" class="schedule-cell">
              {{ nurse[`day_${day.date}`] || '-' }}
          </div>
          <div class="actions">
            <el-button type="primary" link @click="handleEdit(nurse)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Edit } from '@element-plus/icons-vue'
import http from '@/api/http'

const router = useRouter()

// 查询参数
const queryParams = ref({
  nurseCode: 'N001',
  year: new Date().getFullYear(),
  month: new Date().getMonth() + 1,
  stage: 1
})

interface DayInfo {
  date: number
  label: string
}

interface ScheduleRow {
  nurseName: string
  nurseCode: string
  [key: string]: string  // 用于动态的日期属性
}

// 排班数据
const scheduleData = ref<ScheduleRow[]>([])

// 日期数组
const days = ref<DayInfo[]>([])

// 初始化日期数组
const initDays = () => {
  const daysArray = []
  const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  
  const start = queryParams.value.stage === 1 ? 1 : 16
  const end = queryParams.value.stage === 1 ? 15 : 31

  for (let i = start; i <= end; i++) {
    const date = new Date(queryParams.value.year, queryParams.value.month - 1, i)
    const weekDay = weekDays[date.getDay() === 0 ? 6 : date.getDay() - 1]
    const monthDay = String(i).padStart(2, '0')
    daysArray.push({
      date: i,
      label: `${weekDay} (${monthDay})`
    })
  }
  days.value = daysArray
}

// 获取班次样式
const getShiftClass = (shift: string | undefined) => {
  const classes: Record<string, string> = {
    '早': 'shift-morning',
    '中': 'shift-noon',
    '晚': 'shift-night',
    '休': 'shift-rest'
  }
  return classes[shift || ''] || ''
}

// 获取排班列表
const getScheduleList = async () => {
  try {
    const url = `api/Workforce/GetWorkforcesDetail?nurseCode=${queryParams.value.nurseCode}&year=${queryParams.value.year}&month=${queryParams.value.month}&stage=${queryParams.value.stage}`
    const response = await http.get(url)
    
    if (response.status && Array.isArray(response.data)) {
      // 按护士分组数据
      const nurseMap = new Map()
      
      response.data.forEach((item: any) => {
        if (!nurseMap.has(item.nurseCode)) {
          nurseMap.set(item.nurseCode, {
          nurseName: item.nurseName,
            nurseCode: item.nurseCode,
            ...Object.fromEntries(days.value.map(day => [`day_${day.date}`, '-']))
          })
        }
        
        const nurseData = nurseMap.get(item.nurseCode)
        nurseData[`day_${item.stage}`] = item.classGroup
      })
      
      scheduleData.value = Array.from(nurseMap.values())
    } else {
      scheduleData.value = [{
        nurseName: queryParams.value.nurseCode,
        nurseCode: queryParams.value.nurseCode,
        ...Object.fromEntries(days.value.map(day => [`day_${day.date}`, '-']))
      }]
      ElMessage.warning('未找到排班数据')
    }
  } catch (error) {
    console.error('获取排班列表失败:', error)
    ElMessage.error('获取排班列表失败')
    scheduleData.value = [{
      nurseName: queryParams.value.nurseCode,
      nurseCode: queryParams.value.nurseCode,
      ...Object.fromEntries(days.value.map(day => [`day_${day.date}`, '-']))
    }]
  }
}

// 处理添加排班
const handleAdd = () => {
  router.push('/domain/WorkforceManage/WorkforceManageTwo')
}

// 处理编辑排班
const handleEdit = (row: any) => {
  // TODO: 实现编辑排班逻辑
  console.log('编辑排班:', row)
}

// 添加重置查询方法
const resetQuery = () => {
  queryParams.value = {
    nurseCode: 'N001',
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    stage: 1
  }
  getScheduleList()
}

// 监听查询参数变化
watch(() => [queryParams.value.stage, queryParams.value.year, queryParams.value.month], () => {
  initDays()
  getScheduleList()
}, { immediate: true })

onMounted(() => {
  initDays()
  getScheduleList()
})
</script>

<style scoped>
.schedule-container {
  padding: 24px;
  background-color: #fff;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.title-section {
  display: flex;
  align-items: baseline;
  gap: 12px;
}

.title-section h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.schedule-grid {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.schedule-header {
  display: flex;
  border-bottom: 1px solid #dcdfe6;
}

.name-cell {
  width: 120px;
  padding: 12px;
  text-align: center;
  border-right: 1px solid #dcdfe6;
  font-weight: normal;
}

.date-cell {
  flex: 1;
  min-width: 100px;
  padding: 12px 8px;
  text-align: center;
  border-right: 1px solid #dcdfe6;
  font-weight: normal;
}

.schedule-body {
  background: white;
}

.schedule-row {
  display: flex;
  border-bottom: 1px solid #dcdfe6;
  position: relative;
}

.schedule-row:last-child {
  border-bottom: none;
}

.schedule-cell {
  flex: 1;
  min-width: 100px;
  padding: 12px 8px;
  text-align: center;
  border-right: 1px solid #dcdfe6;
}

.shift-badge {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.shift-morning {
  color: #67C23A;
  background-color: #f0f9eb;
}

.shift-noon {
  color: #409EFF;
  background-color: #ecf5ff;
}

.shift-night {
  color: #E6A23C;
  background-color: #fdf6ec;
}

.shift-rest {
  color: #909399;
  background-color: #f4f4f5;
}

.actions {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  display: none;
}

.schedule-row:hover .actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}
</style>

